package service

import (
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/httpmvc/service"
	"ssnotify/common/constant"
	"ssnotify/common/utils"

	"ssnotify/common/dto"
	"ssnotify/internal/data/action"
	"ssnotify/internal/notify/models"
	"ssnotify/internal/notify/models/command"
	"ssnotify/internal/notify/models/query"
)

type NotifyConfig struct {
	notifyConfig *models.NotifyConfig
	service.Service
}

func (e *NotifyConfig) SetNotifyConfigModel(model *models.NotifyConfig) *NotifyConfig {
	e.notifyConfig = model
	return e
}

func (e *NotifyConfig) AddNotifyConfig(req *command.NotifyConfigAddReq) (one models.NotifyConfig, err error) {
	req.Generate(&one)
	err = e.notifyConfig.Add(&one)
	return
}

func (e *NotifyConfig) EditNotifyConfig(req *command.NotifyConfigModReq) (err error) {
	if err = e.notifyConfig.FindOne(e.notifyConfig, dto.MakeCondition(query.NotifyConfigGetReq{Id: req.Id})); err != nil {
		return
	}
	req.Generate(e.notifyConfig)
	err = e.notifyConfig.Mod(e.notifyConfig)
	return
}

func (e *NotifyConfig) DeleteNotifyConfig(c *command.NotifyConfigDelReq) error {
	return e.notifyConfig.Delete(e.notifyConfig, dto.MakeCondition(query.NotifyConfigGetReq{IdIn: c.Ids}))
}

func (e *NotifyConfig) InvokeNotifyConfig(req *command.NotifyConfigInvokeReq) (err error) {
	if err = e.notifyConfig.FindOne(e.notifyConfig, dto.MakeCondition(query.NotifyConfigGetReq{Id: req.Id})); err != nil {
		return
	}
	sn := utils.GetStringValueFiled(req.Data, "sn")
	if len(sn) == 0 {
		return
	}
	//设备分组缓存
	deptId, _ := env.Cache.HashGet(constant.DeviceDeptCache, sn)
	if len(deptId) == 0 {
		deptId = constant.DefaultGroupId
	}
	// 有个叫强烈的人要求有分组名
	groupIdName, _ := utils.GroupIdName(e.Orm, []string{deptId})
	//缓存最新的分组id
	req.Data["deptId"] = deptId
	req.Data["deptName"] = groupIdName[deptId]
	action.ExecuteNotifyConfig(e.Orm, *e.notifyConfig, req.Data)
	return
}
